$.xpkWindow = {};
xpk.Windows = {};

xpk.Window = function(options){
	var _this = {
		options: {
				element: null,
				width: 500,
				height: 'auto',
				className: '',
				autofocus: true,
				html: '<div><h1>Header</h1><p>Content</p></div>'
		},
		bReady: false,
		show: function(options){
			
			var overlay = true;			
			
			if(!options) var options = {};
			
			if(!this.bReady){
				var w = createMarkup.call(this);
				if(!w){
					alert('Could\'t open window: Wrapper element is undefined.');
					return false;
				};
			}
			
			if(this.opened && this === $.xpkWindow && !this.ajax){
				return;
			} else if($.xpkWindow.opened && $.xpkWindow != this) {
				$.xpkWindow.hide(1);
				overlay = false;
			} else if(this.opened && this.ajax){
				return this.loadContent();
			};
			
			if(options.title) {
				this.setTitle(options.title);
			};
			if(options.html) {
				this.setContent(options.html);
			};
			
			w = options.w || this.options.width;
			h = options.h || this.options.height;

			this.wrapper.css({
				visibility: 'hidden',
				top: 0,
				left: 0,
				display: 'block'
			});
			
			this.contentWrapper.css({'width': w, 'height':h});
			
			var _hgt = [10, this.contentWrapper.height()];
			var _top = getTopPosition.apply(this, [_hgt]);
			var _h = this.contentWrapper.outerHeight();
			this.contentWrapper.addClass('xpk-win-show').css({'width': 10, 'height':10});
			
			if(overlay) {
				$.showModalOverlay(200, 0.85,
					function(){
						animateBox.apply(_this,[w,_h, _top]);
					});
			} else {
				animateBox.apply(_this,[w,_h, _top]);
			};
			
			
			$.xpkWindow = this;
			return this;
		},

		hide: function(quick){
			this.wrapper.css({
				display: 'none'
			});
			
			if(!quick) {
				$.hideModalOverlay();
			};
			
			$(window).unbind('resize.reposition');
			
			this.opened = false;
			this.ajax = false;
			$(document).unbind('keyup.keyboardListiner');
			if(this.options.hide) this.options.hide.call(this);
		},

		setTitle: function(txt){
			if(!this.bReady) createMarkup.call(this);
			var text = txt.split(':');
			var string = 
			this.title.html(text[0] + (text[1] ? ': <strong>' + text[1] + '</span>' : '') );
			this.options.title = txt;
		},

		setContent: function(html){
			if(!this.bReady) createMarkup.call(this);
			this.content.empty().append(html);
		},
		
		update: function(html){
			if(!this.bReady) createMarkup.call(this);
			this.setContent(html);
		},
		
		confirm: function(){
			if(this.options.confirm) this.options.confirm.call(this);
		},

		cancel: function(){
			if(this.options.cancel) this.options.cancel.call(this);
		},
		
		get: function(options){
			this.setContent('<div class="xpk-win-loading"></div>');
			this.ajax = options;
			this.show();
		},
		
		loadContent: function(url, callback){
			$.ajax(this.ajax);			
		},
		
		setOptions: function(options){
			$.extend(this.options, options || {});
		},
		
		showPreloader: function(){
			var _css = {
				opacity: 0,
				height: this.content.innerHeight()
			};
			
			if(!this.preloader) {
				this.preloader = $('<div class="xpk-window-preloader" />');
			};
			this.content.css('position', 'relative');
			this.preloader.css(_css);
			this.preloader.appendTo(this.content);
			this.preloader.fadeTo(200, 0.8);
		},
		
		hidePreloader: function(){
			this.content.css('position', '');
			this.preloader.remove();
		}


	};
	
	var keyboardListiner = function(event){
		if(event.keyCode == 27) _this.cancel();
	};
	
	var createMarkup = function(){
		var winHTML = '<div class="xpk-mwindow-wrap"><table class="xpk-mwindow">\
			<tr><td class="tl">&nbsp;</td><td class="tl2">&nbsp;</td><td class="tm">&nbsp;</td><td class="tr2"></td><td class="tr"></td></tr>\
			<tr><td class="ml">&nbsp;</td><td class="xpk-mwindow-content" colspan="3"><div class="xpk-mwindow-content">\
				<div class="xpk-win-head clearfloat">\
					<h4 class="xpk-win-title">Window title</h4>\
					<button class="xpk-close-button">x</button>\
				</div>\
				<div class="xpk-win-content clearfloat">\
				</div>\
			</div></td><td class="mr">&nbsp;</td></tr>\
			<tr><td class="bl">&nbsp;</td><td class="bl2">&nbsp;</td><td class="bm">&nbsp;</td><td class="br2" valign=top>&nbsp;</td><td class="br" valign=top>&nbsp;</td></tr>\
			</table></div>';
		var _css = {
			left: '0',
			position: 'absolute',
			top: '0px',
			width: '100%',
			zIndex: 1000
		};
		if(this.options.element) {			
			if(typeof this.options.element == 'string') {
				this.options.element = $$(this.options.element);
			};
			this.wrapper = this.options.element;
			if(!this.wrapper.length) {
				return false;
			};
		} else {
			this.wrapper = $('<div></div>').attr({
					id: 'WMSWinWrapper',
					className: this.options.className
				}).appendTo(document.body);
			this.wrapper.html(winHTML);
		};
		this.wrapper.css(_css);
		this.contentWrapper = this.wrapper.find('div.xpk-mwindow-wrap');
		
		this.contentCell = this.wrapper.find('.xpk-mwindow-wrap');
		
		this.content = this.contentWrapper.find('div.xpk-win-content');
		this.header = this.contentWrapper.find('div.xpk-win-head');
		this.title = this.contentWrapper.find('.xpk-win-title');
		this.closeButton = this.contentWrapper.find('.xpk-close-button'); //.add(closeLinks);
		
		this.closeButton.bind('click', function(){
			_this.cancel();
			return false;
		});
		
		if(this.options.html) this.content.html(this.options.html);
		if(this.options.title) this.title.text(this.options.title);
		this.bReady = true;
		
		return true;
	};
	
	var setupWindow = function(width, height, top){
		this.opened = true;
		$(window).bind('resize.reposition', reposition);
		$(document).bind('keyup.keyboardListiner', keyboardListiner);
		if(this.options.show) this.options.show.call(this);
	};


	var animateBox = function(w,h, top){
		var _duration = 250;
		var _easing = jQuery.easing['easeOutExpo'] ? 'easeOutExpo' : 'swing';
		
		this.wrapper.css({
			visibility: 'visible', 
			height: 'auto',
			top: top[0] + 'px'
		});	
		
		this.contentWrapper.animate({
			width: w,
			height: h + 'px'
		}, {
			easing: _easing,
			duration: _duration,
			complete: function(){
				var $element = $(this);
				$element.removeClass('xpk-win-show').css({height: _this.options.height});
				setupWindow.apply(_this, [w, h, top]);
				if(_this.ajax) _this.loadContent();
			}
		});

	
		this.wrapper.animate({top: top[1] + 'px'},{
			easing: _easing,
			duration: _duration,
			complete: function(){
				var $element = $(this);
				$element.css({overflow: ''});
			}
		});
	};
	
	var getTopPosition = function(_hgt){
		var _top = [];

		var _winHeight = $(document.body).height();
		var _topOffset = $(window).scrollTop();
		
		_top[0] = _winHeight / 2 - _hgt[0] / 2;
		_top[0] +=  _topOffset;
		
		_top[1] = _hgt[1] > _winHeight ? 25 : _winHeight/2 - _hgt[1]/2;
		_top[1] += _topOffset;
		if(_top[1] < 10) _top[1] = 10;
		
		return _top;
	};
	
	var reposition = function(animate){
		var _duration = 250;
		var _top = getTopPosition([0, _this.wrapper.height()]);
		var _easing = jQuery.easing['easeOutExpo'] ? 'easeOutExpo' : 'swing';
		
		_this.wrapper.animate({top: _top[1]},{
			easing: _easing,
			duration: _duration
		});		
					
	};

	_this.setOptions(options);
	if(_this.options.element) createMarkup.call(_this);
	if(_this.options.init) _this.options.init.call(_this);
	
	return _this;
	
};

//dimScreen()
//by Brandon Goldman
(function($){
	var resizeCheck = function(){
		$.WMSOverlay.css({
			height: $(document).height()
		});
	};
	
    //dims the screen	
    $.showModalOverlay = function(speed, opacity, callback) {
        
        if(typeof speed == 'function') {
            callback = speed;
            speed = null;
        }

        if(typeof opacity == 'function') {
            callback = opacity;
            opacity = null;
        }

        if(speed < 1) {
            var placeholder = opacity;
            opacity = speed;
            speed = placeholder;
        }
        
        if(opacity >= 1) {
            var placeholder = speed;
            speed = opacity;
            opacity = placeholder;
        }

        speed = (speed > 0) ? speed : 500;
        opacity = (opacity > 0) ? opacity : 0.5;
		
		var _css = [{
			display: 'block',
			height: $(document).height() + 'px',
			left: '0px',
			opacity: 0,
			position: 'absolute',
			top: '0px',
			width: '100%',
			zIndex: 999
		},{
			display: 'block',
			opacity: 0,
			height: $(document).height()
		}];
		
        if(!this.WMSOverlay) {
			this.WMSOverlay = this('<div></div>').attr({
                id: 'dimScreen'
            }).css(_css[0]).appendTo(document.body);
			$.data($.WMSOverlay[0], 'options', { fade_opacity: opacity, speed: speed});			
			
			if(window.ie6){
				this.WMSOverlayFix = this('<iframe></iframe').attr({
					tabindex: -1,
					frameborder: 0,
					src: 'javascript:false;'
				}).css(_css[0]).appendTo(document.body);
			};
		} else {
			this.WMSOverlay.css(_css[1]);
			if(this.WMSOverlayFix){
				this.WMSOverlayFix.css(_css[1]);
			};
		};
		$(window).bind('resize', resizeCheck);


		if(window.ie6){
			speed = 0;
		};
		this.WMSOverlay.fadeTo(speed, opacity, callback);
		this.WMSOverlay.visible = 1;
		return this.WMSOverlay;
    };
    
    //stops current dimming of the screen
    $.hideModalOverlay = function(callback) {
        var x = this.WMSOverlay;
		var opt = $.data($.WMSOverlay[0], 'options');
        var opacity = opt.fade_opacity;
        var speed = window.ie6 ? 0 : opt.speed;
        x.fadeOut(speed, function() {
			if($.WMSOverlayFix){
				$.WMSOverlayFix.css({
					display: 'none'
				});
			};
            if(typeof callback == 'function') callback();
        });
		$(window).unbind('resize', resizeCheck);
		this.WMSOverlay.visible = 0;
    }
})(jQuery);